import { Sorter } from './Sorter';

//定义链表里的节点
class Node {
  //有可能是Node 有可能是null 初始值是null
  next: Node | null = null;

  constructor(public data: number) {}
}

export class LinkedList extends Sorter {
  head: Node | null = null;

  add(data: number): void {
    //创建节点
    const node = new Node(data);

    //当链表为空时
    //this.head = null -> false
    //!this.head -> true
    if (!this.head) {
      //新创建的node为head
      this.head = node;
      return;
    }

    //当链表不为空时
    let tail = this.head;

    //后移到next = null 时为最后的节点
    //直到tail.next=false时跳出循环
    while (tail.next) {
      //最后的节点会一直往后移
      tail = tail.next;
    }

    //找到最后的节点后保存新的节点
    tail.next = node;
  }

  //获取长度
  get length(): number {
    if (!this.head) {
      return 0;
    }

    let length = 1;
    let node = this.head;

    while (node.next) {
      length++;
      node = node.next;
    }

    return length;
  }

  //获取链表里某一个
  at(index: number): Node {
    if (!this.head) {
      throw new Error('Index out of bounds: 超出界限');
    }

    let counter = 0;
    let node: Node | null = this.head;

    while (node) {
      if (counter === index) {
        return node;
      }

      counter++;
      node = node.next;
    }

    throw new Error('Index out of bounds: 超出界限');
  }

  //对比
  compare(leftIndex: number, rightIndex: number): boolean {
    if (!this.head) {
      throw new Error('List is empty');
    }

    return this.at(leftIndex).data > this.at(rightIndex).data;
  }

  //交换
  swap(leftIndex: number, rightIndex: number): void {
    const leftNode = this.at(leftIndex);
    const rightNode = this.at(rightIndex);

    const leftHand = leftNode.data;
    leftNode.data = rightNode.data;
    rightNode.data = leftHand;
  }

  //检测排序是否正确
  print(): void {
    if (!this.head) {
      return;
    }

    let node: Node | null = this.head;

    while (node) {
      console.log(node);
      node = node.next;
    }
  }
}
